package cn.daixi.web.sys.service.impl;

import cn.daixi.web.common.exception.ValidateException;
import cn.daixi.web.sys.dto.LoginReq;
import cn.daixi.web.sys.dto.RegisterReq;
import cn.daixi.web.sys.dto.TableColumnRes;
import cn.daixi.web.sys.entity.User;
import cn.daixi.web.sys.mapper.UserMapper;
import cn.daixi.web.sys.service.UserService;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.Cookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public User findById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User login(LoginReq loginReq) {
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();

        userWrapper.eq(User::getUserName, loginReq.getUserName());
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String digestHex = md5.digestHex(loginReq.getPassword());
        userWrapper.eq(User::getPassword, digestHex);
        User user = userMapper.selectOne(userWrapper);
        if (user == null) {
            throw new ValidateException("用户名密码错误");
        }
        return user;
    }

    @Override
    public User register(RegisterReq registerReq) {
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getUserName, registerReq.getUserName());

        User user = userMapper.selectOne(userWrapper);
        if (user != null) {
            throw  new ValidateException("用户已存在");
        }

        User myUser = new User();
        myUser.setUserName(registerReq.getUserName());
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String digestHex = md5.digestHex(registerReq.getPassword());
        myUser.setPassword(digestHex);
        Integer id = userMapper.insert(myUser);

        return userMapper.selectById(id);
    }

    public Cookie setLogin(User user){
        Cookie myCookie = new Cookie("user", user.getUserId().toString());
        myCookie.setPath("/");
        myCookie.setMaxAge(3600); // 设置为1小时（3600秒）
        return myCookie;
    }


    @Override
    public List<User> list() {
        List<User> users = userMapper.selectList(null);
        return users;
    }

}
